//
//  PlayViewController.m
//  My1A2B
//
//  Created by sun ives on 2009/12/28.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PlayViewController.h"
#import "My1A2BAppDelegate.h"
#import "HistoryTableViewController.h"
#import "MyNumberPadView.h"
#import "define_tw.h"
#import <libxml/encoding.h>
#import <libxml/xmlwriter.h>



@implementation PlayViewController
@synthesize fNumber, bSubmit, bFrontProcess, bBackHome, lTitle, lAnswer, m_answerCount, m_appDelegate, myNumberPadView, contentView;

- (IBAction) makeKeyboardGoAway{
	//[fNumber resignFirstResponder];
	[myNumberPadView removeFromSuperview];
}

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
		//[textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
	self.m_appDelegate = [[UIApplication sharedApplication] delegate];
	//myNumberPadView.hidden = YES;
    return self;
}


// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
	[super loadView];
	//CGSize size = CGSizeMake(320, 1000);
	//UIScrollView *view = (UIScrollView*)(self.view);
	//[view setContentSize:size];
	int answerCount = [m_appDelegate.core getAnswerCount];
	NSString *title = [NSString stringWithFormat:SUB_TITLE, answerCount];
	lTitle.text = title;
	//[title release];
	[lTitle setTextColor:[UIColor blackColor]];
	NSString *number_placeHolder = [[NSString alloc] initWithFormat:NUMBER_PLACEHOLDER, answerCount];
	fNumber.placeholder = number_placeHolder;
	[fNumber setTextColor:[UIColor blackColor]];
	[number_placeHolder release];
	char *answer = [m_appDelegate.core getAnswer];
	NSString *nAnswer = [[NSString alloc] initWithCString:answer];
	lAnswer.text = nAnswer;
	[nAnswer release];
}
- (void)viewDidAppear:(BOOL)animated{
	[(UIScrollView*)self.view flashScrollIndicators];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.title = VIEW_PLAY;
    UIBarButtonItem *addButtonItem = [[UIBarButtonItem alloc] initWithTitle:VIEW_HISTORY style:UIBarButtonItemStylePlain target:self action:@selector(frontHistory:)];
    self.navigationItem.rightBarButtonItem = addButtonItem;
    [addButtonItem release];
	
	CGRect frame = self.view.frame;
	frame.size.height = 460;
	//frame.origin.y = 20;
	self.view.frame = frame;
	frame = contentView.frame;
	[(UIScrollView*)self.view setContentSize:frame.size];
	//contentView.backgroundColor = [UIColor greenColor];
	//[fNumber becomeFirstResponder];
	
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (IBAction)guess:(UIButton *)sender{
	//[fNumber resignFirstResponder];
	NSUInteger length = [fNumber.text length];
	if (length < m_answerCount){
		NSString *title = [[NSString alloc] initWithFormat:WARNING];
		NSString *msg = [[NSString alloc] initWithFormat:NOT_ENOUGH, m_answerCount];
		[self alert:title message:msg tag:3];
		[msg release];
		[title release];
		return;
	}
	char *chGuess = (char *)malloc(m_answerCount+1);
	memset(chGuess, '\0', m_answerCount+1);
	[fNumber.text getCString:chGuess maxLength:m_answerCount+1 encoding:NSUTF8StringEncoding];
	int guessCount = [m_appDelegate.core getGuessCount];
	char *chResult = [m_appDelegate.core compare:chGuess];
	NSString *sResult = [[NSString alloc] initWithFormat:@"%d.%@ %s", guessCount, fNumber.text, chResult];
	NSString *sAnswer = [[NSString alloc] initWithFormat:@"%d.%@ %dA0B", guessCount, fNumber.text, m_answerCount];
	if ([sResult isEqualToString:sAnswer]){
		int minute = [m_appDelegate.core getPlayTimeMinute];
		int second = [m_appDelegate.core getPlayTimeSecond];
		NSString *title = [[NSString alloc] initWithFormat:CONGRAGURATION];
		NSString *msg = [[NSString alloc] initWithFormat:GUESS_RIGHT, fNumber.text, guessCount, minute, second];
		[fNumber resignFirstResponder];
		UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:@"繼續玩", @"結束", nil];
		myAlert.tag = 2;
		[myAlert show];
		[myAlert release];
		[msg release];
		[title release];
		//strResult *result = [m_appDelegate.core getResult];
		//int no = [history getGameNo]+1;
		//[history setGame:no count:result->count answer:result->answer startTime:result->startTime guessTime:result->guessTime guess:result->guess];
		[m_appDelegate writeXML];
	}
	float processWidth = 90.0f;
	float processHeight = 30.0f;
	float processOffset = 10.0f;
	float processStartPoint[2] = {10.0f, 130.0f};
	int cell = guessCount%3;
	cell = (guessCount%3 == 0)?2:cell-1;
	float processStartX = processStartPoint[0]+((processWidth+processOffset)*cell);
	int row = guessCount/3;
	row = (guessCount%3 == 0)?row-1:row;
	float processStartY = processStartPoint[1]+((processHeight+processOffset)*row);

	UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(processStartX, processStartY, processWidth, processHeight)];
	label.adjustsFontSizeToFitWidth = YES;
	label.textAlignment = UITextAlignmentCenter;
	label.backgroundColor = [UIColor clearColor];
	[label setText:sResult];
	[sResult release];
	[sAnswer release];
	free(chResult);
	free(chGuess);
	[label setTextColor:[UIColor redColor]];
	[self.view addSubview:label];
	[label release];
	fNumber.text = @"";
}
- (BOOL)checkNumber:(NSUInteger)length input:(NSString*)input{
	if (length+1 > m_answerCount){
		NSString *title = [[NSString alloc] initWithFormat:WARNING];
		NSString *msg = [[NSString alloc] initWithFormat:TOO_MUCH, m_answerCount];
		[self alert:title message:msg tag:1];
		[msg release];
		[title release];
		//fNumber.text = [fNumber.text substringToIndex:m_answerCount];
		return NO;
	}
	BOOL bDup = NO;
	NSRange range;
	range.location = 0;
	range.length = 1;
	unichar *chInput = (unichar*)malloc(sizeof(unichar)*2);
	memset(chInput, '\0', sizeof(unichar)*2);
	[input getCharacters:chInput range:range];
	//NSLog(@"%c", *chInput);
	for (int i = 0; i < length; i++) {
		unichar ch = [fNumber.text characterAtIndex:i];
		if (ch == *chInput) {
			bDup = YES;
			break;
		}
	}
	free(chInput);
	if (bDup) {
		return NO;
		/*
		NSString *title = [[NSString alloc] initWithFormat:WARNING];
		NSString *msg = [[NSString alloc] initWithFormat:NUMBER_DUPLICATION];
		[self alert:title message:msg];
		[msg release];
		[title release];
		fNumber.text = [fNumber.text substringToIndex:length-1];
		*/
	}
	return YES;
}
- (IBAction)pressNumber:(UIButton *)sender{
	NSUInteger length = [fNumber.text length];
	NSString *number = sender.currentTitle;
	if ([number isEqualToString:@"C"]) {
		myNumberPadView.hidden = YES;
		//[self.view sendSubviewToBack:myNumberPadView];
		//[myNumberPadView removeFromSuperview];
		return;
	}else if ([number isEqualToString:@"X"]) {
		if ([fNumber.text length] > 0){
			fNumber.text = [fNumber.text substringToIndex:length-1];
		}
	}else{
		if (length > 0 && ![self checkNumber:length input:number]) {
			return;
		}		
		NSString *before = fNumber.text;
		NSString *after = [before stringByAppendingString:number];
		fNumber.text = after;
	}
}
- (void)frontHistory:(id)sender{
	if (myNumberPadView && !myNumberPadView.hidden){
		myNumberPadView.hidden = YES;
	}
	if ([m_appDelegate.core isNewRecord]){
		[m_appDelegate.historyTableViewController reloadData];
		[m_appDelegate.core setNewRecordFalse];
	}
	[self.navigationController pushViewController:m_appDelegate.historyTableViewController animated:YES];	
}
- (IBAction)backHome:(UIButton *)sender{

}
- (void)alert:(NSString *)title message:(NSString *)msg tag:(NSInteger)tag{
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:@"確定", nil];
	alertView.tag = tag;
	[alertView show];
	[alertView release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	NSInteger tag = alertView.tag;
	if (tag == 2){
		switch (buttonIndex) {
			case 0:
				[m_appDelegate.core reStart:m_answerCount];
				[self loadView];
				break;
			case 1:
				fNumber.enabled = NO;
				break;
			default:
				break;
		}
	}
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
	if (textField == fNumber){
		if (myNumberPadView.hidden) {
			myNumberPadView.hidden = NO;
			return NO;
		}

		CGRect frame = CGRectMake(0, 480, 320, 230);
		myNumberPadView.frame = frame;
		[self.view addSubview:myNumberPadView];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.75];
		[myNumberPadView setFrame:CGRectMake(0, 200, 320, 230)]; 
		[UIView commitAnimations];
/*
		
		// Begin animations to move TextFileds into view.
		CGRect frame = CGRectMake(0, 270, 320, 230);
		myNumberPadView.frame = frame;
		//myNumberPadView = [[MyNumberPadView alloc] initWithFrame:frame];
		//[myNumberPadView setBackgroundColor:[UIColor yellowColor]];
		//[myNumberPadView setAlpha:0.87];
	

		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:5.75];
		frame.origin.x = 0;
		frame.origin.y = 270;
		//myNumberPadView.frame = frame;

		//[UIView beginAnimations:nil context:nil];
		//[UIView setAnimationDuration:5.5]; 
		//[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:myNumberPadView cache:YES];
 
		//[UIView commitAnimations];
		[m_appDelegate.window addSubview:myNumberPadView];
		//[self.view addSubview:myNumberPadView];
		[UIView commitAnimations];
*/
	}
	return NO;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
	if (textField == fNumber){
		myNumberPadView.hidden = YES;
	}
	return YES;
}
- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[m_appDelegate release];
	[myNumberPadView release];
	[contentView release];
    [super dealloc];
}


@end
